package com.example.gustavo.hello;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.test.ApplicationTestCase;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceView;
import android.widget.Toast;

import com.example.gustavo.hello.model.ParamObj;
import com.example.gustavo.hello.model.TestObj;
import com.example.gustavo.hello.utils.DateUtil;
import com.example.gustavo.hello.utils.MathUtils;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.jose4j.jwk.OctJwkGenerator;
import org.jose4j.jwk.OctetSequenceJsonWebKey;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.lang.JoseException;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLOutput;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.transform.Source;

import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Action2;
import rx.functions.Action3;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }

    public static final String TAG = "ApplicationTest";

    public void testContext(){

        assert getContext() != null;
    }

    public void testJWT() throws JoseException {

        OctetSequenceJsonWebKey octetSequenceJsonWebKey = OctJwkGenerator.generateJwk(256);
        octetSequenceJsonWebKey.setKeyId("weisd");

        // Create the Claims, which will be the content of the JWT
        JwtClaims claims = new JwtClaims();
//        claims.setIssuer("Issuer");  // who creates the token and signs it
//        claims.setAudience("Audience"); // to whom the token is intended to be sent
        claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
//        claims.setGeneratedJwtId(); // a unique identifier for the token
//        claims.setIssuedAtToNow();  // when the token was issued/created (now)
//        claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
        claims.setSubject("subject"); // the subject/principal is whom the token is about
        claims.setClaim("email", "mail@example.com"); // additional claims/attributes about the subject can be added
//        List<String> groups = Arrays.asList("group-one", "other-group", "group-three");
//        claims.setStringListClaim("groups", groups); // multi-valued claims work too and will end up as a JSON array

        // A JWT is a JWS and/or a JWE with JSON claims as the payload.
        // In this example it is a JWS so we create a JsonWebSignature object.
        JsonWebSignature jws = new JsonWebSignature();

        // The payload of the JWS is JSON content of the JWT Claims
        jws.setPayload(claims.toJson());

        // The JWT is signed using the private key
        jws.setKey(octetSequenceJsonWebKey.getKey());

        // Set the Key ID (kid) header because it's just the polite thing to do.
        // We only have one key in this example but a using a Key ID helps
        // facilitate a smooth key rollover process
        jws.setKeyIdHeaderValue(octetSequenceJsonWebKey.getKeyId());

        // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setDoKeyValidation(false);//不校验key 例如长度

        // Sign the JWS and produce the compact serialization or the complete JWT/JWS
        // representation, which is a string consisting of three dot ('.') separated
        // base64url-encoded parts in the form Header.Payload.Signature
        // If you wanted to encrypt it, you can simply set this jwt as the payload
        // of a JsonWebEncryption object and set the cty (Content Type) header to "jwt".
        String jwt = jws.getCompactSerialization();


        // Now you can do something with the JWT. Like send it to some other party
        // over the clouds and through the interwebs.
        System.out.println("JWT: " + jwt);

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.addHeader("Authorization", "Bearer " + jwt);
        asyncHttpClient.addHeader("client-id", "da");

        asyncHttpClient.get("http://192.168.0.33:1323/jwt/info", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                System.out.println("result= " + responseString);
            }
        });

    }

    public void testFor() {

        RequestParams params = new RequestParams();
        params.put("acode", "sh600519");
        params.put("code", "600519");

        List<ParamObj> list = new ArrayList<>();
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));
        list.add(new ParamObj("adfs", "dfhs"));
        list.add(new ParamObj("code", "dfhs"));
        list.add(new ParamObj("3sdf", "dfhs"));

        Collections.sort(list);

        StringBuilder sb = new StringBuilder();

        long l1 = System.nanoTime();
        for (int j = 0; j < 1000; j++) {

            for (int i = 0; i < list.size(); i++) {
                ParamObj paramObj = list.get(i);
                String name = paramObj.name;
                Object value = paramObj.value;

            }
        }
        System.out.println("for1 coast = " + (System.nanoTime() - l1) / 1000);

        long l = System.nanoTime();
        for (int i = 0; i < 1000; i++) {

            for (ParamObj paramObj : list) {
                String name = paramObj.name;
                Object value = paramObj.value;
            }
        }
        System.out.println("for coast = " + (System.nanoTime() - l)/1000);



    }

    public void testBean(){

        String json = "";
        Gson gson = new Gson();
        TestObj testObj = gson.fromJson(json, TestObj.class);
        System.out.println("testObj = " + testObj.toString());

    }

    public void testRxAndroid(){

        /*Observable.from(new String[]{"hello","world"})
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {

                        return s + "me";
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        System.out.println("print " + s);
                    }
                });*/

        Observable.from(getList())

                .observeOn(Schedulers.newThread())


                .doOnError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                })

                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                        System.out.println("print " + s);
                    }
                });



    }

    public List<String> getList(){

        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add("hello " + i);
        }

        return list;
    }

    public void testHttp(){

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();


        String url = "http://api.liangtou.com/stock/hello";
        asyncHttpClient.get(getContext(),url,new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.e(TAG,"statusCode = " + statusCode+" result="+responseString);

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.e(TAG,"statusCode = " + statusCode+" result="+responseString);

            }
        });

    }

    public void testDefault(){

        HashMap hashMap = new HashMap();
        int size = hashMap.size();
         System.out.println("size = " + size);

    }

    public void testMatch(){

        String email1 = "liangtou@liangtou.com.cc.cn";
        String email2 = "liangtou@liangtou.com.cn";
        String email3 = "liangtou@liangtoucom";
        String email4 = "liangtou@l.com";
        String email5 = "l@.com";
        String email6 = "lngtou@l.com";

        System.out.println("isEmail = "+email1 +" :"+ isEmail(email1));
        System.out.println("isEmail = "+email2 +" :"+ isEmail(email2));
        System.out.println("isEmail = "+email3 +" :"+ isEmail(email3));
        System.out.println("isEmail = "+email4 +" :"+ isEmail(email4));
        System.out.println("isEmail = "+email5 +" :"+ isEmail(email5));
        System.out.println("isEmail = "+email6 +" :"+ isEmail(email6));


    }
    public boolean isEmail(String email){
        String regularExpression = "^\\w++@\\w++(.\\w++)++$";
        Pattern pattern = Pattern.compile(regularExpression);
        Matcher matcher = pattern.matcher(email);

        return matcher.find();
    }

    public void testPrint(){

        System.out.println("打印正等腰三角");
        int i ,j;
        for(i=1;i<=5;i++){
            for(j=5;j>i;j--){
                System.out.print(" ");
            }
            for(j=0;j<i*2-1;j++){
                System.out.print("*");
            }
            System.out.println();
        }

    }

    public void testSort(){
        ArrayList<Integer> nums = new ArrayList<Integer>();

        for (int i = 0; i < 1000 ; i++) {

            nums.add(new Random().nextInt(2000));
        }

        Integer[] arrays = new Integer[1000];
        Integer[] integers = nums.toArray(arrays);


        long start = System.currentTimeMillis();
        SortUtils.quickSort(integers);
        System.out.println(" coast =" + (System.currentTimeMillis() - start));

        long start1 = System.currentTimeMillis();
        Arrays.sort(integers);
        System.out.println(" coast1 =" + (System.currentTimeMillis() - start1));

        for (int num : integers) {
            System.out.println("coastsort =" + num);
        }


    }

    public void testDen(){
        float density = getContext().getResources().getDisplayMetrics().density;
        System.out.println("density = " + density);
    }

    public void testFloat(){
        float f = 10.25f;
        f++;
        System.out.println(f);
    }
    public void testDateFormatUtil(){

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//        String format = sdf.format(new Date());
//        System.out.println("format = " + format);
        Date date = new Date();
        date.setDate(31);

//        String formatDate = DateFormatUtil.formatDate(date.getTime());
        String formatDate = DateUtil.formatDate(date.getTime());
        System.out.println("formatDate = " + formatDate);


    }
    public void testGetDeviceID(){

        TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        System.out.println("tm.getDeviceId() = " + tm.getDeviceId());
    }

    public void testMathUtil(){

//        String s = MathUtils.formatSize(1254.587452);
//        String s1 = MathUtils.formatSize(5879546.3578965);
//        String s2 = MathUtils.formatSize(6546854103563544.324165);
//        String s3 = MathUtils.formatSize(-54168.24864);
//        String s4 = MathUtils.formatSize(-58671676835435.546);
//        String s5 = MathUtils.formatNumber(54851.5468521, 5);
//        System.out.println("s="+s+"s1="+s1+"s2="+s2+"s3="+s3+ "s4 = " + s4+" s5="+s5);

        DecimalFormat df = new DecimalFormat("#.00");
        String format = df.format(0.65874);
        System.out.println("format = " + format);

    }

    public void testAsyncHttp(){

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        //cookie store
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getContext());
        asyncHttpClient.setCookieStore(myCookieStore);

        RequestParams params = new RequestParams();
        params.add("key","value");

        asyncHttpClient.post("url",params,new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
        asyncHttpClient.post("",new BaseJsonHttpResponseHandler<String>() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, String response) {

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, String errorResponse) {

            }

            @Override
            protected String parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                return null;
            }
        });
    }




    public void testDemo() {
        String name = "name";
        HashMap<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("name", "李菲儿");
        hashMap.put("name","黄晓明");


        for (String s : hashMap.keySet()) {
            System.out.println("k="+s+" v="+hashMap.get(s));
        }


//        for (Map.Entry<String, String> s : hashMap.entrySet()) {
//            System.out.println("key="+s.getKey()+" value="+s.getValue());
//        }
        assertEquals(2, 2);
    }
    public void testBase64(){
        String str = "123";
        /*
        byte[] encode = Base64.encode(str.getBytes(), Base64.DEFAULT);
        byte[] decode = Base64.decode(encode, Base64.DEFAULT);
        Drawable drawable = getContext().getResources().getDrawable(R.drawable.ic_drawer);
        Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

        Gson gson = new Gson();
        String toJson = gson.toJson(bitmap);
        System.out.println("encode.toString() = " + toJson);
        */

        ArrayList<Integer> strings = new ArrayList<Integer>();
        Type genericSuperclass = strings.getClass().getGenericSuperclass();
        Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        for (Type type1 : ((ParameterizedType) genericSuperclass).getActualTypeArguments()) {

            System.out.println("type = " + type1);
        }
    }
    public void testTrim(){
        Math.random();
        String str = null;

        System.out.println("trim = " + str.trim());

    }

}
